<template>
	<view class="chat-container">
		<view class="chat-box">
			<scroll-view class="chat-messages" scroll-y id="chatMessages" @scrolltolower="scrollToBottom"
				:scroll-top="scrollTop" scroll-with-animation="true">
				<view v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
					<view v-if="message.type === 'user'" class="message user">
						<image class="avatar" src="/static/bk3.jpg" />
						<view class="message-content">
							<rich-text :nodes="message.text"></rich-text>
							<view class="message-time">{{ formatTime(message.time) }}</view>
						</view>
					</view>
					<view v-if="message.type === 'ai'" class="message ai">
						<image class="avatar" src="/static/logo.png" />
						<view class="message-content">
							<rich-text :nodes="getDisplayText(message)"></rich-text>
							<view class="message-time">{{ formatTime(message.time) }}</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="input-container">
				<input type="text" name="" v-model="inputText" class="input-search">
				<button @click="sendMessage">
					<view class="send">
						<text>发送</text>
					</view>
				</button>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				scrollTop: 9999,
				messages: [],
				inputText: '',
				typingMessage: null,
				typingIndex: 0,
				fullText: ''
			};
		},
		mounted() {
			// this.$nextTick(() => {
			// 	this.scrollToBottom();
			// });
		},
		methods: {
			scrollToBottom() {
				console.log("底部")
				this.$nextTick(() => {
					this.scrollTop = this.scrollTop;
				});
			},
			async sendMessage() {
				if (this.inputText.trim() === '') {
					uni.showToast({
						title: '你没有输入消息呢',
						icon: 'error',
						duration: 1000
					});
					return;
				}
				this.messages.push({
					text: this.inputText,
					type: 'user',
					time: new Date()
				});
				this.$nextTick(() => {
					this.scrollToBottom();
					this.inputText = '';
				});

				try {
					const response = await this.request({
						url: 'https://api.chatanywhere.tech/v1/chat/completions',
						method: 'POST',
						data: {
							model: "gpt-3.5-turbo",
							messages: [{
								role: "user",
								content: this.inputText
							}]
						},
						header: {
							'Content-Type': 'application/json',
							'Authorization': 'Bearer sk-jg5PWekaVH4zTwCzsco5V6VIJIhyi5SvpOsH85MRNQ3ofgcN'
						}
					});

					const aiMessage = {
						text: '',
						type: 'ai',
						time: new Date(),
						fullText: response.data.choices[0].message.content
					};
					this.messages.push(aiMessage);

					this.fullText = aiMessage.fullText;
					this.scrollToBottom();
					this.typingIndex = 0;
					this.typingMessage = setInterval(() => {
						if (this.typingIndex < this.fullText.length) {
							aiMessage.text += this.fullText[this.typingIndex];
							this.typingIndex++;
							// this.scrollToBottom();
						} else {
							clearInterval(this.typingMessage);
							this.typingMessage = null;
						}
					}, 100); // 调整间隔时间以控制打字速度

					
				} catch (error) {
					console.error('Error sending message:', error);
				}

				this.inputText = '';
			},
			request(options) {
				return new Promise((resolve, reject) => {
					uni.request({
						...options,
						success: (res) => resolve(res),
						fail: (err) => reject(err)
					});
				});
			},
			getDisplayText(message) {
				this.scrollToBottom()
				// 获取最后一个消息对象
				const lastMessage = this.messages[this.messages.length - 1];
				// 检查最后一个消息对象是否与当前消息对象相同
				if (lastMessage === message) {
					return message.fullText.substring(0, this.typingIndex);
				} else {
					return message.fullText;
				}
			},
			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			}
		}
	}
</script>
<style scoped>
	.chat-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		width: 100vw;
		background-color: #f5f7fa;
		flex-direction: column;
	}

	.chat-box {
		height: 95vh;
		width: 100vw;
		display: flex;
		flex-direction: column;
		background-color: #ffffff;
		border-radius: 10px;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
		overflow: hidden;
		margin-bottom: 60px;
		/* 为输入框留出空间 */
	}

	.chat-messages {
		flex: 1;
		overflow-y: auto;
		padding: 10px;
		display: flex;
		flex-direction: column;
		background-color: #f5f7fa;
	}

	.message {
		padding-top: 15px;
		display: flex;
		align-items: flex-start;
		margin-bottom: 10px;
	}

	.user {
		align-self: flex-end;
		padding-right: 10px;
		flex-direction: row-reverse;
	}

	.ai {
		align-self: flex-start;
		flex-direction: row;
	}

	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin: 0 10px;
		object-fit: fill;
	}

	.message-content {
		max-width: 70%;
		padding: 10px;
		border-radius: 15px;
		line-height: 1.5;
		font-size: 14px;
		position: relative;
	}

	.user .message-content {
		background-color: #007aff;
		color: white;
		border-bottom-right-radius: 5px;
	}

	.ai .message-content {
		background-color: #e5e5ea;
		color: black;
		border-bottom-left-radius: 5px;
	}

	.message-time {
		font-size: 12px;
		color: #888;
		position: absolute;
		bottom: -20px;
		left: 0px;
	}

	.input-container {
		display: flex;
		padding: 10px;
		border-top: 1px solid #ccc;
		background-color: whitesmoke;
		position: fixed;
		width: 100%;
		bottom: 40px;
		left: 0;
		border-radius: 10px;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	}

	input {
		flex: 1;
		margin-right: 10px;
		/* 	padding: 10px; */
		padding-left: 25px;
		border: 1px solid #ccc;
		border-radius: 20px;
		background-color: #fff;
		font-size: 14px;
	}

	.input-search {
		border: none;
		height: 40px;
	}

	.send {
		font-size: 13px;
	}

	button {
		padding: 5px;
		margin-right: 20px;
		border: none;
		cursor: pointer;
		width: 16%;
		align-items: center;
		justify-content: center;
		background-color: limegreen;
	}

	button:hover {
		background-color: whitesmoke;
	}

	.send-icon {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 20px;
		width: 20px;
	}

	.send-svg {
		width: 24px;
		height: 24px;
		fill: white;
	}
</style>